import { Application, codo } from "egg";
import WeWorkBaseService from "./WeWorkBaseService";
import CodoError from "../CodoError";
import { WeWork } from "./type";

export default class Message extends WeWorkBaseService {
	constructor(
		protected config: codo.WeWork.IWeWorkConfig,
		private accessToken: string,
		protected app: Application
	) {
		super(config, app);
	}

	/** 创建url */
	private getUrlAndToken() {
		const url = `https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=${this.accessToken}`;
		return { url };
	}

	/**
	 *发送一条文本消息到一个用户
	 *
	 * @param {string} appAccessToken
	 * @param {string} userid 用户id
	 * @param {string} content 发送内容
	 * @return {*}
	 * @memberof PlatFormQiyeWeixinBaseMessageService
	 */
	async sendTextMessageToOneUser(userid: string, content: string) {
		const { url } = this.getUrlAndToken();

		const agentId = this.config.agentId;
		const sendData: codo.WeWork.ISendTextMessageRequest = {
			touser: userid,
			msgtype: "text",
			agentid: agentId,
			text: {
				content: content,
			},
		};
		const res = await this.curl<codo.WeWork.ISendMessageResponse>(url, {
			method: "POST",
			contentType: "json",
			dataType: "json",
			data: sendData,
			timeout: [30000, 30000],
		});

		if (res.data.errcode === 0) {
			return res.data;
		}
		this.app.logger.error("[wework 单人发送文本消息] 错误 %s", res.data.errmsg);
		throw new CodoError(res.data.errcode + res.data.errmsg);
	}

	/** 发送webhook消息
	 * - 存文本
	 */
	async sendWebhookTextMessage(key: string, text: string) {
		const url = `https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=${key}`;
		const data = {
			msgtype: "text",
			text: {
				content: text,
				mentioned_list: ["@all"],
			},
		};

		const res = await this.curl<codo.WeWork.ISendMessageResponse>(url, {
			method: "POST",
			contentType: "json",
			dataType: "json",
			data,
			timeout: [30000, 30000],
		});

		if (res.data.errcode === 0) {
			return res.data;
		}
		this.app.logger.error("[wework 发送机器人消息] 错误 %s", res.data.errmsg);
		throw new CodoError(res.data.errmsg);
	}
	/**
	 *发送一条文本消息到应用可见的所有用户
	 *
	 *  - 要求在应用下的用户
	 *
	 * @param {string} appAccessToken
	 * @param {string} content 发送内容
	 * @return {*}
	 * @memberof PlatFormQiyeWeixinBaseMessageService
	 */
	async sendTextMessageToAllUser(content: string) {
		const { url } = this.getUrlAndToken();

		const agentId = this.config.agentId;
		const sendData: WeWork.ISendTextMessageRequest = {
			touser: "@all",
			msgtype: "text",
			agentid: agentId,
			text: {
				content: content,
			},
		};
		const res = await this.app.curl<WeWork.ISendMessageResponse>(url, {
			method: "POST",
			contentType: "json",
			dataType: "json",
			data: sendData,
			timeout: [30000, 30000],
		});

		if (res.data.errcode === 0) {
			return res.data;
		}
		this.app.logger.error("[wework 所有人发送文本消息] 错误 %s", res.data.errmsg);
		throw new CodoError(res.data.errmsg);
	}

	/**
	 *发送一条文本卡片消息到一个用户
	 *
	 * 卡片消息的展现形式非常灵活，支持使用br标签或者空格来进行换行处理，也支持使用div标签来使用不同的字体颜色，
	 * 目前内置了3种文字颜色：灰色(gray)、高亮(highlight)、默认黑色(normal)，将其作为div标签的class属性即可，具体用法请参考上面的示例。
	 *
	 * @param {string} userid 用户id
	 * @param {WeWork.ISendTextCardMessageRequest['textcard']} textcard
	 * @return {*}
	 * @memberof PlatFormQiyeWeixinBaseMessageService
	 */
	async sendTextCardMessageToOneUser(
		userid: string,
		textcard: WeWork.ISendTextCardMessageRequest["textcard"]
	) {
		const { url } = this.getUrlAndToken();

		const agentId = this.config.agentId;
		const sendData: WeWork.ISendTextCardMessageRequest = {
			touser: userid,
			msgtype: "textcard",
			agentid: agentId,
			textcard: textcard,
		};
		const res = await this.app.curl<WeWork.ISendMessageResponse>(url, {
			method: "POST",
			contentType: "json",
			dataType: "json",
			data: sendData,
			timeout: [30000, 30000],
		});

		if (res.data.errcode === 0) {
			return res.data;
		}
		this.app.logger.error("[wework 单人发送文本卡片消息] 错误 %s", res.data.errmsg);
		throw new CodoError(res.data.errmsg);
	}

	/**
	 * 单人发送markdown消息推送
	 *
	 * @param {string} userid
	 * @param {qiwei.ISendMarkdownMessageRequest["markdown"]["content"]} content
	 * @return {*}
	 * @memberof PlatFormQiyeWeixinBaseMessageService
	 */
	async sendMarkdownMessageToOneUser(
		userid: string,
		content: WeWork.ISendMarkdownMessageRequest["markdown"]["content"]
	) {
		const { url } = this.getUrlAndToken();

		const agentId = this.config.agentId;
		const sendData: WeWork.ISendMarkdownMessageRequest = {
			touser: userid,
			msgtype: "markdown",
			agentid: agentId,
			markdown: {
				content: content,
			},
		};
		const res = await this.app.curl<WeWork.ISendMessageResponse>(url, {
			method: "POST",
			contentType: "json",
			dataType: "json",
			data: sendData,
			timeout: [30000, 30000],
		});

		if (res.data.errcode === 0) {
			return res.data;
		}
		this.app.logger.error("[wework 单人发送markdown消息] 错误 %s", res.data.errmsg);
		throw new CodoError(res.data.errmsg);
	}
}
